package example.plugins.automaton;

import java.util.ArrayList;

import framework.automaton.Logic;
import framework.automaton.State;
import framework.grid.Grid;
import framework.grid.Location;

/**
 * Defines the game logic that is used in Conway's Game of life
 * @author Bill Ge, May Zhai, Alex Yoo
 *
 */
public class ConwayLogic implements Logic{
	
	/**
	 * implementation of the model to be used within Conway's game of life
	 * <br> Below rules are used:</br>
	 * <br>1)Any live cell with fewer than two live neighbours dies, as if caused by under-population.</br>
	 * <br>2)Any live cell with two or three live neighbours lives on to the next generation.</br>
	 * <br>3)Any live cell with more than three live neighbours dies, as if by overcrowding.</br>
	 * <br>4)Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.</br>
	 *  
	 * 
	 * @param grid: the grid that the cell is contained in
	 * @param loc: location of the cell to be looked at
	 * @return the next state that the current Cell will turn into
	 */
	public State advanceTurn(Grid grid, Location loc){
		ConwayState currentState = (ConwayState)grid.get(loc);
		ArrayList<State> neighbors = grid.getNeighbors(loc);
		int liveNeighbors = 0;
		
		for(int i = 0; i <neighbors.size(); i++){
			if(((ConwayState) neighbors.get(i)).getCurrentState()==Constants.ALIVE){
				liveNeighbors++;
			}
		}
		
		if(currentState.getCurrentState()==Constants.ALIVE){
			if(liveNeighbors<2){
				return new ConwayState(Constants.DEAD); 
			}else if(liveNeighbors>=2 && liveNeighbors<=3){
				return new ConwayState(Constants.ALIVE);
			}else{
				return new ConwayState(Constants.DEAD);
			}
		}else{
			if(liveNeighbors==3){
				return new ConwayState(Constants.ALIVE);
			}
		}
		return new ConwayState(Constants.DEAD);
	}
}
